/*
 *    Copyright 2022 jacky4631 shen ji email:121659050@qq.com
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dataoke.shoppingguide.app773026.util;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebView;
import android.widget.Toast;

import com.dataoke.shoppingguide.app773026.R;
import com.kongzue.dialogx.dialogs.MessageDialog;
import com.kongzue.dialogx.util.TextInfo;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;
/**
 *
 * @author: shen ji
 * @date: 2022/3/15
 * @email: 121659050@qq.com
 * @wechat: jacky4631
 */
public class AppUtil {

    private final static String TAG = AppUtil.class.getSimpleName();

    /**
     * 获取当前app version code
     */
    public static long getAppVersionCode(Context context) {
        long appVersionCode = 0;
        try {
            PackageInfo packageInfo = context.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                appVersionCode = packageInfo.getLongVersionCode();
            } else {
                appVersionCode = packageInfo.versionCode;
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "[getAppVersionCode]-error：" + e.getMessage());
        }
        return appVersionCode;
    }

    public static void openApp(Context context, String url) {
        if(url.contains("taobao.com")) {
            openTaoBaoApp(context, url);
        }
//        else if(url.contains("jd.com") || url.startsWith("openapp.jdmobile://")) {
//            try {
//                openJingDongApp(view, url);
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
//        }
//        else if(url.contains("pinduoduo.com")) {
//            openPinDuoDuoApp(view, url);
//        }
//        else if(url.contains("vip.com") || url.contains("vipshop://")) {
//            openVipApp(view, url);
//        }
//        else {
//            if(url.startsWith("http")) {
//                view.loadUrl(url);//调用webview本身的loadUrl方法
//            }
//
//        }

    }

    public static void openTaoBaoApp(Context context, String url) {
        if (checkPackage(context, "com.taobao.taobao")) {
            if (url.startsWith("https://")) {
                url = url.replaceFirst("https://", "taobao://");
            }
            if (url.startsWith("http://")) {
                url = url.replaceFirst("http://", "taobao://");
            }
            if (url.startsWith("tbopen://")) {
                url = url.replaceFirst("tbopen://", "taobao://");
            }
            String finalUrl = url;
//            MessageDialog.show("离开"+context.getString(R.string.app_name)+"，打开淘宝", "", "继续", "取消").setOkButton((baseDialog, v) -> {
                DialogHelper.showLoadingDialog(context,"正在打开淘宝APP");

                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri uri = Uri.parse(finalUrl);
                intent.setData(uri);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
//                return false;
//            }).setCancelButton((baseDialog, v) -> false).setOkTextInfo(getOkTextInfo()).setCancelTextInfo(getCancelTextInfo()).setCancelable(false);
        }else {
            Toast.makeText(context, "未安装淘宝APP", Toast.LENGTH_SHORT).show();
        }
    }

    public static void openJingDongApp(Context context, WebView view, String url) throws JSONException {
        if (checkPackage(context, "com.jingdong.app.mall")) {
//            url = "openapp.jdmobile://virtual?params=%7B%22sourceValue%22:%220_productDetail_97%22,%22des%22:%22productDetail%22,%22skuId%22:%22"+id+"%22,%22category%22:%22jump%22,%22sourceType%22:%22PCUBE_CHANNEL%22%7D";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("category", "jump");
            jsonObject.put("des", "getCoupon");
            jsonObject.put("url", url);

            url = "openapp.jdmobile://virtual?params=" + jsonObject.toString();
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri uri = Uri.parse(url);
            intent.setData(uri);
            context.startActivity(intent);
        }else {
            if(url.startsWith("openapp.jdmobile://")) {
                Toast.makeText(context, "未安装京东APP", Toast.LENGTH_SHORT).show();
            } else {
                view.loadUrl(url);
            }

        }
    }

    public static void openPinDuoDuoApp(Context context, WebView view, String url) {
        if (checkPackage(context, "com.xunmeng.pinduoduo")) {
            if (url.startsWith("https://mobile.yangkeduo.com/app.html?launch_url=")) {
                url = url.replaceFirst("https://mobile.yangkeduo.com/app.html?launch_url=", "pinduoduo://com.xunmeng.pinduoduo/");
            }
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri uri = Uri.parse("pinduoduo://com.xunmeng.pinduoduo/" + url);
            intent.setData(uri);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } else {
            view.loadUrl(url);
        }
    }

    public static void openVipApp(Context context, WebView view, String url){
        if (checkPackage(context, "com.achievo.vipshop")) {
            if(url.startsWith("vipshop://")) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri uri = Uri.parse(url);
                intent.setData(uri);
                context.startActivity(intent);
            } else {
                view.loadUrl(url);
            }
        } else {
            if(url.startsWith("http")) {
                view.loadUrl(url);
            }

        }
    }

    public static void openMeituanApp(Context context, String url) {
        if (checkPackage(context, "com.sankuai.meituan")) {
            DialogHelper.showLoadingDialog(context,"正在打开美团APP");
            Intent intent = new Intent();
            Uri uri = Uri.parse(url);
            intent.setData(uri);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }else {
            Toast.makeText(context, "未安装美团APP", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 微信开放平台-移动应用id
     * */
    public static String getWxAppId(Context context) {
        if(isTaoShengQian(context)) {
          return context.getString(R.string.wx_app_id_tsq);
        }
        return context.getString(R.string.wx_app_id_jkj);
    }

    public static boolean isTaoShengQian(Context context) {
        return "淘省钱".equals(context.getString(R.string.app_name));
    }

    public static void openWxBz(Context context) {
        if (checkPackage(context, "com.tencent.mm")) {
            MessageDialog.show("离开"+context.getString(R.string.app_name)+"，打开微信", "", "继续", "取消").setOkButton((baseDialog, v) -> {
                DialogHelper.showLoadingDialog(context,"正在打开微信小程序“群壁纸”", 2000);
                IWXAPI api = WXAPIFactory.createWXAPI(context,getWxAppId(context));
                WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
                req.userName = context.getString(R.string.wx_small_app_bz_id); // 填小程序原始id
                req.path = "";                  //拉起小程序页面的可带参路径，不填默认拉起小程序首页
                req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
                api.sendReq(req);
                return false;
            }).setCancelButton((baseDialog, v) -> false).setOkTextInfo(getOkTextInfo()).setCancelTextInfo(getCancelTextInfo()).setCancelable(false);
        }else {
            Toast.makeText(context, "未安装微信APP", Toast.LENGTH_SHORT).show();
        }
    }

    public static void openWxMeituan(Context context, String url) {
        if (checkPackage(context, "com.tencent.mm")) {
            MessageDialog.show("离开"+context.getString(R.string.app_name)+"，打开微信", "", "继续", "取消").setOkButton((baseDialog, v) -> {
                DialogHelper.showLoadingDialog(context,"正在打开微信小程序“美团红包”", 2000);
                IWXAPI api = WXAPIFactory.createWXAPI(context,getWxAppId(context));
                WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
                req.userName = context.getString(R.string.wx_mei_tuan_id); // 填小程序原始id
                req.path = url;                  //拉起小程序页面的可带参路径，不填默认拉起小程序首页
                req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
                api.sendReq(req);
                return false;
            }).setCancelButton((baseDialog, v) -> false).setOkTextInfo(getOkTextInfo()).setCancelTextInfo(getCancelTextInfo()).setCancelable(false);

        }else {
            Toast.makeText(context, "未安装微信APP", Toast.LENGTH_SHORT).show();
        }
    }

    public static TextInfo getOkTextInfo() {
        TextInfo textInfo = new TextInfo();
        textInfo.setFontColor(Color.rgb(72,61,139));
        textInfo.setBold(true);
        textInfo.setFontSize(16);
        return textInfo;
    }
    public static TextInfo getCancelTextInfo() {
        TextInfo textInfo = new TextInfo();
        textInfo.setFontColor(Color.rgb(0,0,0));
        textInfo.setBold(true);
        textInfo.setFontSize(16);
        return textInfo;
    }
    public static boolean checkPackage(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            context.getPackageManager().getApplicationInfo(packageName, PackageManager
                    .MATCH_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }

    }

    /**
     * 启动到应用商店app详情界面
     *
     *
     com.android.vending     Google Play
     com.tencent.android.qqdownloader    应用宝
     com.qihoo.appstore   360手机助手
     com.baidu.appsearch 百度手机助
     com.xiaomi.market  小米应用商店
     com.wandoujia.phoenix2 豌豆荚
     com.huawei.appmarket  华为应用市场
     com.taobao.appcenter  淘宝手机助手
     com.hiapk.marketpho 安卓市场
     cn.goapk.market 安智市场
     *
     * @param appPkg  目标App的包名
     * @param marketPkg 应用商店包名 ,如果为""则由系统弹出应用商店列表供用户选择,否则调转到目标市场的应用详情界面，某些应用商店可能会失败
     */
    public void launchAppDetail(Context context, String appPkg, String marketPkg) {
        try {
            if (TextUtils.isEmpty(appPkg)) return;
            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (!TextUtils.isEmpty(marketPkg)) {
                intent.setPackage(marketPkg);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
